package com.lock.immersive.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lock.immersive.exception.BusinessException;
import com.lock.immersive.mapper.AddressMapper;
import com.lock.immersive.mapper.UserMapper;
import com.lock.immersive.pojo.domain.Address;
import com.lock.immersive.pojo.dto.AddressDto;
import com.lock.immersive.service.AddressService;
import com.lock.immersive.utils.ErrorCode;
import com.lock.immersive.utils.JWT;
import com.lock.immersive.utils.ResponseApi;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhao
 * @description 针对表【address】的数据库操作Service实现
 * @createDate 2023-07-02 00:04:03
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {
    @Resource
    public UserMapper userMapper;
    @Resource
    public AddressMapper addressMapper;

    @Override
    public ResponseApi<Object> insertAddress(AddressDto addressDto, HttpServletRequest request) {
        Address address = new Address();
        BeanUtils.copyProperties(addressDto, address);
        String token = request.getHeader("token");
        String userId = JWT.getTokenId(token);
        address.setUserId(userId);
        int insert = addressMapper.insert(address);
        if (insert > 0) {
            return ResponseApi.success();
        } else {
            throw new BusinessException(ErrorCode.INSERT_ERROR);
        }
    }

    @Override
    public ResponseApi<List<Address>> getAddress(HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = JWT.getTokenId(token);
        List<Address> addressList = addressMapper.getAddressByUserId(userId);
        return ResponseApi.success(addressList);
    }
}




